package com.hrd.common.util.file;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class DownloadUtil {
	/**
	 * 
	 * @param url  文件链接
	 * @param filePath 文件保存地址
	 * @throws IOException
	 */
	public static String downloadFile(String url, String filePath, String fileFullName) throws IOException {
		URL theURL = new URL(url);
		URLConnection con = theURL.openConnection();
		String urlPath = con.getURL().getFile();
//		String fileFullName = "123.jpg";
		String path = "";
		if (fileFullName != null) {
			byte[] buffer = new byte[4 * 1024];
			int read;
			path = filePath + "/" + fileFullName ;
			File fileFolder = new File(filePath);
			if (!fileFolder.exists()) {
				fileFolder.mkdirs();
			}
			File file = new File(path);
			if (file.exists()) {
				return path;
			}
			InputStream in = con.getInputStream();
			FileOutputStream os = new FileOutputStream(path);
			while ((read = in.read(buffer)) > 0) {
				os.write(buffer, 0, read);
			}
			os.close();
			in.close();
		}
		return path;
	}

	/**
	 * 根据url获取文件流
	 * @param url
	 * @return
	 */
	public static InputStream downloadFile(String url){
		InputStream in = null;
		try {
			URL theURL = new URL(url);
			URLConnection con = theURL.openConnection();
			in = con.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return in;
	}

	/**
	 * 模板文件下载文件
	 *
	 * @param file
	 * @param response
	 * @param isDelete
	 */
	public static void downloadFileByLocal(HttpServletRequest request, File file, HttpServletResponse response, boolean isDelete) {
		// 清空response
		response.reset();
		try (
				InputStream in = new FileInputStream(file);
				OutputStream out = response.getOutputStream();
		) {

			String fileName = file.getName();
			response.reset();
			//response.setHeader("content-disposition", "attachment;filename=" + new String((fileName).getBytes("UTF-8"), "ISO8859-1"));
			String userAgent = request.getHeader("user-agent");
			if (userAgent != null && userAgent.indexOf("Edge") >= 0) {
				fileName = URLEncoder.encode(fileName, "UTF8");
			} else if (userAgent.indexOf("Firefox") >= 0 || userAgent.indexOf("Chrome") >= 0
					|| userAgent.indexOf("Safari") >= 0) {
				fileName = new String((fileName).getBytes("UTF-8"), "ISO8859-1");
			} else {
				fileName = URLEncoder.encode(fileName, "UTF8"); //其他浏览器
			}

			// 以流的形式下载文件。
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

			//写文件
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}

			if (isDelete) {
				file.delete();        //是否将生成的服务器端文件删除
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
